package tau.pimpmyfreedb.common;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Hashtable;
import java.util.Map;

public class Network
{
	// hide constructor since it is a static class
	private Network()
	{
	}

	public static String GetQueryStringValue(String url, String key) {
		Map<String, String> query = GetQueryString(url);
		return query.get(key);
	}

	public static Map<String, String> GetQueryString(String url) {
		Hashtable<String, String> res = new Hashtable<String, String>();

		// validate input
		if (url == null)
			return res;

		// search for the query string beginning
		int begin = url.indexOf("?");
		if (begin == -1)
			begin = url.indexOf("#");
		if (begin == -1)
			return res;

		// get the query string
		String query = url.substring(begin + 1);
		String[] queryArr = query.split("&");

		// populate res
		for (String keyValue : queryArr)
		{
			int indexOfEq = keyValue.indexOf("=");
			String key = keyValue.substring(0, indexOfEq);
			String value = keyValue.substring(indexOfEq + 1);
			res.put(key, value);
		}

		return res;
	}

	public static String SendHttpGetRequest(String url) throws IOException {
		String res = null;
		String charset = "UTF-8";

		URLConnection connection = new URL(url).openConnection();
		connection.setRequestProperty("Accept-Charset", charset);
		InputStream response = connection.getInputStream();

		StringBuilder str = new StringBuilder();
		int ch;
		while ((ch = response.read()) != -1)
		{
			str.append((char) ch);
		}

		response.close();
		res = str.toString();

		return res;
	}
}
